// 封装axios
import axios from "axios";
import local from "@/store/local";
import { message } from "./message";
import router from "@/router";

// 创建axios实例
const service = axios.create({
  baseURL: "http://localhost:8888/job",
  timeout: 15000, //15秒
});

// 添加请求拦截器
service.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    if (local.getToken()) {
      config.headers.token = local.getToken();
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
service.interceptors.response.use(
  function (response) {
    console.log(response, "response===");
    // 对响应数据做点什么
    const res = response.data;
    console.log(res, "原始数据 请求");
    if (response.status == 200) {
      if (res.code == 200) {
        return res;
      } else if (res.code == 401) {
        // 没有权限
        message.error(res.message);
        // 退出登录
        router.push("/login");
      } else if (res.code == 402) {
        message.error(res.message);

        router.push("/login");
      } else if (res.code == 500) {
        message.error(res.message);
        router.push("/login");
      }
    } else {
      message.error(res.message);
    }
    return res;
  },
  function (error) {
    // 对响应错误做点什么
    message.error(error.message);
    return Promise.reject(error);
  }
);

// export default service;

let base = ""; //前置路径

// 传送json格式的post请求
export const postRequest = (url, params) => {
  return service({
    method: "post",
    url: `${base}${url}`,
    data: params,
  });
};

//传送json格式的put请求
export const putRequest = (url, params) => {
  return service({
    method: "put",
    url: `${base}${url}`,
    data: params,
  });
};

//传送json格式的get请求
export const getRequest = (url, params) => {
  return service({
    method: "get",
    url: `${base}${url}`,
    data: params,
  });
};
//传送json格式的delete请求
export const deleteRequest = (url, params) => {
  return service({
    method: "delete",
    url: `${base}${url}`,
    data: params,
  });
};
